package net.lab1024.sa.admin.module.r.controller;

import cn.dev33.satoken.annotation.SaCheckPermission;
import cn.hutool.core.text.csv.*;
import cn.hutool.json.JSONUtil;
import cn.idev.excel.FastExcel;
import com.alibaba.fastjson.JSON;
import io.swagger.v3.oas.annotations.Operation;
import lombok.extern.slf4j.Slf4j;
import net.lab1024.sa.admin.module.business.goods.domain.form.GoodsImportForm;
import net.lab1024.sa.base.common.domain.ResponseDTO;
import net.lab1024.sa.base.common.exception.BusinessException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.FileSystemResource;
import org.springframework.core.io.ResourceLoader;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.core.io.Resource;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.*;

import static java.io.File.separator;

@RestController
@Slf4j
public class DownloadController {
    @Autowired
    private ResourceLoader resourceLoader;
    @GetMapping("/r/download-template")
    public ResponseEntity<Resource> downloadTemplate() throws IOException {
        // 从 resources 目录下获取文件
        Resource resource = resourceLoader.getResource("classpath:plot.xls");
        try {
            File file = resource.getFile();
            if (file.exists()) {
                return ResponseEntity.ok()
                        .header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=\"模板.xls\"")
                        .contentType(MediaType.APPLICATION_OCTET_STREAM)
                        .body(resource);
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
        return ResponseEntity.notFound().build();
    }

    @Operation(summary = "导入 @author 卓大")
    @PostMapping("/r/importPlots")
    public ResponseDTO<String> importGoods(@RequestParam MultipartFile file) throws IOException {
        List<LinkedHashMap<String,String>> dataList = new ArrayList<>();
        Path tempFile = Files.createTempFile("prefix", ".tmp");
        file.transferTo(tempFile);
        File hutoolCsv = tempFile.toFile();
        CsvReader reader = new CsvReader(hutoolCsv, setCsvReadConfig());
        reader.setContainsHeader(true);
        List<String> list0 = new LinkedList<>();
        List<String> list1 = new LinkedList<>();
        List<String> list2 = new LinkedList<>();
        List<String> list3 = new LinkedList<>();
        reader.stream().forEach(csvRow -> {
            List<String> rawList = csvRow.getRawList();
            list0.add(rawList.get(0));
            list1.add(rawList.get(1));
            list2.add(rawList.get(2));
            list3.add(rawList.get(3));
        });
        System.out.println(JSON.toJSONString(list0));
        System.out.println(JSON.toJSONString(list1));
        System.out.println(JSON.toJSONString(list2));
        System.out.println(JSON.toJSONString(list3));
        return ResponseDTO.okMsg("成功导入" + list0.size() + "条，具体数据为：" + JSON.toJSONString(dataList));
    }



    public static CsvReadConfig setCsvReadConfig(){
        CsvReadConfig csvReadConfig = new CsvReadConfig();
        // 设置 文本分隔符，文本包装符，默认双引号'"'
        csvReadConfig.setTextDelimiter('\t');
        // 字段分割符号，默认为逗号
        csvReadConfig.setFieldSeparator('\t');
        // 设置注释符号
        // csvReadConfig.setCommentCharacter('#');
        // CSV文件是否包含表头(因为表头不是数据内容)
        csvReadConfig.setContainsHeader(true);
        // 或者使用如下配置设置表头开始行号，-1L代表无表头
        // csvReadConfig.setHeaderLineNo(1L);
        //设置开始的行（包括），默认0，此处为原始文件行号
        // csvReadConfig.setBeginLineNo(0);
        // 是否跳过空白行，默认为true
        // csvReadConfig.setSkipEmptyRows(true);
        // 设置每行字段个数不同时是否抛出异常，默认false
        // csvReadConfig.setErrorOnDifferentFieldCount(false);
        // 将表头的别称对转换为对应的字段
        Map<String, String> headerAlias = new LinkedHashMap<>();
        headerAlias.put("序号", "Subject");
        headerAlias.put("姓名", "Condition");
        headerAlias.put("性别", "Mass");
        csvReadConfig.setHeaderAlias(headerAlias);
        return csvReadConfig;
    }

    /*public static void main(String[] args) throws REngineException, REXPMismatchException {
        RConnection conn = new RConnection();
        conn.eval("library('grafify')");

        // 或者从Java传递数据
        double[] Subject = {1, 1, 2,2};
        double[] Condition = {1, 2, 1,2};
        double[] Mass = {10, 20, 30,40};
        conn.assign("Subject", Subject);
        conn.assign("Condition", Condition);
        conn.assign("Mass", Mass);
        conn.eval("df <- data.frame(Subject=Subject, Condition=Condition, Mass=Mass)");
        REXP eval = conn.eval("df");
        System.out.println(JSONUtil.parse(eval.asNativeJavaObject()));
        REXP eval3 = conn.eval("myplot1 = plot_befafter_colours(\n" +
                "  data = df,\n" +
                "  xcol = Condition,\n" +
                "  ycol = Mass,\n" +
                "  match = Subject, \n" +
                "  symsize = 3,\n" +
                "  fontsize = 13,\n" +
                "  ColPal = \"light\",\n" +
                "  ColRev = T\n" +
                ") +\n" +
                "labs(title = \"123\")");// z轴变量
        REXP eval4 = conn.eval("ggsave('my_plot1.pdf', plot = myplot1, width = 8, height = 6, units = 'in')");
        conn.close();
    }*/
}
